package org.itboys.basetemplate.service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.itboys.basetemplate.entity.Favorite;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.member.entity.Member;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.mongodb.morphia.query.Query;
import org.springframework.stereotype.Service;

/**
 *	我的收藏
 */
@Service
public class FavoriteService extends BaseService<Favorite, Long>{

	private static final long serialVersionUID = 1L;
	
	@Resource(name = "memberDS")
	private MongoDataSource ds;
	
	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}
	/**
	 * 
	 * @param request
	 * @param response
	 * @param objId
	 * @param type 1-特产，2-景点，3-名宿，4-农家乐
	 */
	public void collect(HttpServletRequest request, HttpServletResponse response, Long objId, Integer type) {
		try {
			Member member = (Member) request.getSession().getAttribute("MEMBER");
			Long memberId = member.getId();
			Map<String, Object> map = new HashMap<>();
			map.put("memberId", memberId);
			map.put("objId", objId);
			map.put("type", type);
			Favorite favorite = getFirst(map);
			String msg = new String();
			int code = 0;
			if (favorite!=null) {
				if (favorite.getIsDeleted()!=null && favorite.getIsDeleted()==1) {
					favorite.setIsDeleted(0);
					msg = "取消收藏成功!";
				} else {
					favorite.setIsDeleted(1);
					msg = "收藏成功!";
					code = 1;
				}
				super.update(favorite);
			} else {
				favorite = new Favorite();
				favorite.setObjId(objId);
				favorite.setMemberId(memberId);
				favorite.setType(type);
				favorite.setIsDeleted(1);
				super.save(favorite);
				msg = "收藏成功!";
				code = 1;
			}
			AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgCodeResultDO(code, msg));
		} catch (Exception e) {
			e.printStackTrace();
			AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "系统异常!"));
		}
	}
	
	/**
	 * 根据条件查询第一条数据
	 * 
	 * @param conditions
	 * @param number
	 */
	public Favorite getFirst(Map<String, Object> param)
	{
		Iterator<String> ite = param.keySet().iterator();
		Query<Favorite> query = getMongoDataSource().createQuery(getEntityClass());
		while (ite.hasNext())
		{
			query = prepareQuery(param, ite, query);
		}
		return query.get();
	}
}
